package main

import (
	"bufio"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
	"time"
)

//var loger *log.Logger

const (
	InitDate = "2006-01-02"
	DateTime = "2006-01-02 15:04:05"
)

func init() {
	createLogFile()
}

func main() {
	TickerDemo()

}

func TickerDemo() {
	ticker := time.NewTicker(60 * time.Second)
	defer ticker.Stop()
	for range ticker.C {
		createLogFile()
		log.Println("------启动文件扫描并转换------")
		//WalkDir("/home/ftpuser/video/")
		WalkDir("/home/ftpuser/video/")
	}
}

func createLogFile() {
	now := time.Now()
	nowDate := now.Format(InitDate)
	file := "./log/" + nowDate + ".txt"
	bool, _ := PathExists("./log/")
	if !bool {
		os.Mkdir("./log/", os.ModePerm)
	} else {
		bool1, _ := PathExists(file)
		if bool1 {
			return
		}
	}
	logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
	if err != nil {
		panic(err)
	}
	log.SetOutput(logFile) // 将文件设置为log输出的文件
	log.SetPrefix("[dav2mp4]")
	log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
	return
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func WalkDir(dir string) {
	now := time.Now()
	filepath.Walk(dir, func(fileName string, fi os.FileInfo, err error) error {
		if !fi.IsDir() {
			ext := path.Ext(fileName)
			name := strings.TrimSuffix(fileName, ext)
			name = strings.ReplaceAll(name, "video", "exchange") + ".mp4"
			name = strings.ReplaceAll(name, "ftpuser", "ftpuser01")
			mp4dir := path.Dir(name)
			//判断mp4存放目录是否存在
			bool, _ := PathExists(mp4dir)
			if !bool {
				os.MkdirAll(mp4dir, os.ModePerm)
				if err != nil && !os.IsExist(err) {
					log.Fatal(err)
				}
			}
			if ext == ".dav" {
				//判断dav是否已经转过了
				fExist, _ := PathExists(name)
				if !fExist {
					left := now.Sub(fi.ModTime())
					if left.Minutes() > 2 {
						c := `ffmpeg -i ` + fileName + ` -vcodec copy -acodec copy ` + name
						log.Println(c)
						ExecCommand(c)
						RemoveOSFile(fileName)
					}
				}
			}
		}
		return nil
	})
}

// ExecCommand 运行命令并实时查看运行结果
func ExecCommand(command string) error {
	cmd := exec.Command("bash", "-c", command)

	stdout, _ := cmd.StdoutPipe()
	stderr, _ := cmd.StderrPipe()

	if err := cmd.Start(); err != nil {
		log.Println("Error:The command is err: ", err.Error())
		return err
	}
	ch := make(chan string, 100)
	stdoutScan := bufio.NewScanner(stdout)
	stderrScan := bufio.NewScanner(stderr)
	go func() {
		for stdoutScan.Scan() {
			line := stdoutScan.Text()
			ch <- line
		}
	}()
	go func() {
		for stderrScan.Scan() {
			line := stderrScan.Text()
			ch <- line
		}
	}()
	var err error
	go func() {
		err = cmd.Wait()
		if err != nil && !strings.Contains(err.Error(), "exit status") {
			log.Println("wait:", err.Error())
		}
		close(ch)
	}()
	for line := range ch {
		log.Println(line)
	}
	return err
}

// ExecCommandWithResult 运行命令并获取结果
func ExecCommandWithResult(command string) string {
	out, err := exec.Command("bash", "-c", command).CombinedOutput()
	if err != nil && !strings.Contains(err.Error(), "exit status") {
		log.Println("err: " + err.Error())
		return ""
	}
	return string(out)
}

//删除指定路径的文件
func RemoveOSFile(fileName string) {
	err := os.Remove(fileName) //删除文件
	if err != nil {
		//如果删除失败则输出 file remove Error!
		log.Println("file remove Error!")
		//输出错误详细信息
		log.Println(err)
	} else {
		//如果删除成功则输出 file remove OK!
		log.Println("file remove OK!")
	}
}
